<template>
  <view class="invoice-list-page">
    <!-- 顶部背景 -->
    <view class="header-bg">
      <view class="nav-bar">
        <view class="back" @click="goBack">
          <text class="iconfont icon-arrow-left"></text>
        </view>
        <text class="title">发票管理</text>
      </view>
      <view class="header-content">
        <view class="total-info">
          <text class="label">已开具发票总金额（元）</text>
          <text class="amount">{{ statistics.totalAmount }}</text>
        </view>
        <view class="stat-row">
          <view class="stat-item">
            <text class="num">{{ statistics.processingCount }}</text>
            <text class="label">开票中</text>
          </view>
          <view class="stat-item">
            <text class="num">{{ statistics.monthCount }}</text>
            <text class="label">本月开票</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 开具新发票按钮 -->
    <view class="new-invoice-btn" @click="goToNewInvoice">
      <image src="/static/image/invoice-add.png" mode="aspectFit" class="icon"></image>
      <text>去开具发票</text>
    </view>

    <!-- 发票记录列表 -->
    <view class="invoice-list">
      <view class="list-header">
        <text class="title">开票记录</text>
      </view>

      <view class="invoice-item" v-for="(item, index) in invoiceList" :key="index" @click="viewInvoiceDetail(item)">
        <view class="invoice-header">
          <view class="left">
            <text class="type">电子发票</text>
            <text class="status" :class="getStatusClass(item.status)">{{
              item.statusText
            }}</text>
          </view>
          <text class="time">{{ item.createTime }}</text>
        </view>
        <view class="invoice-content">
          <view class="info-row">
            <text class="label">发票抬头：</text>
            <text class="value">{{ item.title }}</text>
          </view>
          <view class="info-row">
            <text class="label">发票内容：</text>
            <text class="value">{{ item.content }}</text>
          </view>
          <view class="info-row">
            <text class="label">纳税人识别号: </text>
            <text class="value">{{ item.code }}</text>
          </view>
          <view class="info-row">
            <text class="label">接收邮箱: </text>
            <text class="value">{{ item.email }}</text>
          </view>
        </view>
        <view class="invoice-footer">
          <text class="amount">￥{{ item.amount }}</text>
          <view class="action-btns" v-if="item.status === 'success'">
            <text class="btn preview" @click.stop="previewInvoice(item)">查看</text>
            <!-- <text class="btn download" @click.stop="downloadInvoice(item)">下载</text> -->
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提示 -->
    <view class="bottom-tips" v-if="invoiceList.length > 0">
      <text>已经到底啦 ~</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="invoiceList.length === 0">
      <image src="/static/image/empty-invoice.png" mode="aspectFit" class="empty-img"></image>
      <text class="empty-text">暂无开票记录</text>
    </view>
   
  </view>
</template>

<script>
import { getInvoiceStatistics, getInvoiceList } from "@/api/invoice.js";
import { downloadFile } from "@/api/file.js";
import config from '@/config.js';

export default {
  data() {
    return {
      invoiceList: [],
      statistics: {
        totalAmount: "0.00",
        processingCount: 0,
        monthCount: 0,
      },
      loading: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      cloudStorage: config.cloudStorage,
      fileUrl: '',
      fileType: '',
      showPreview: false,
      previewUrl: ''
    };
  },
  onLoad() {
    this.getInvoiceStatistics();
    this.getInvoiceList();
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.pageNum = 1;
    this.hasMore = true;
    this.getInvoiceList().then(() => {
      uni.stopPullDownRefresh();
    });
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.pageNum++;
      this.getInvoiceList();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    goToNewInvoice() {
      uni.navigateTo({
        url: "/pages/invoice/invoice",
      });
    },
    viewInvoiceDetail(item) {
      // TODO: 查看发票详情
      console.log("查看发票详情", item);
    },
    async downloadInvoice(item) {
      if (!item.fileUrl) {
        uni.showToast({
          title: '发票文件不存在',
          icon: 'none'
        });
        return;
      }

      try {
        const fileUrl = this.cloudStorage + item.fileUrl;
        
        // 创建一个隐藏的a标签来下载文件
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = fileUrl;
        link.setAttribute('download', `发票_${item.createTime}.pdf`); // 假设是PDF文件，可以根据实际情况修改
        document.body.appendChild(link);
        
        link.click();
        
        document.body.removeChild(link);
        
        uni.showToast({
          title: '开始下载',
          icon: 'success'
        });
      } catch (error) {
        console.error('下载失败:', error);
        uni.showToast({
          title: '下载失败',
          icon: 'none'
        });
      }
    },
    async previewInvoice(item) {
      if (!item.fileUrl) {
        uni.showToast({
          title: '发票文件不存在',
          icon: 'none'
        });
        return;
      }

      const fileUrl = this.cloudStorage + item.fileUrl;
      
      // 在新窗口中打开PDF预览
      window.open(fileUrl, '_blank');
    },
    async getInvoiceStatistics() {
      try {
        const res = await getInvoiceStatistics();

        this.statistics = {
          totalAmount: res.total_invoiced_amount.toFixed(2),
          processingCount: res.processing_invoice_count,
          monthCount: res.current_month_invoice_count,
        };
      } catch (error) {
        console.error("获取发票统计数据失败", error);
      }
    },
    // 获取开票记录列表
    async getInvoiceList() {
      if (this.loading) return;
      this.loading = true;
      try {
        const res = await getInvoiceList(this.pageNum, this.pageSize);

        const list = res.map(item => ({
          id: item.id,
          type: item.invoiceType === 1 ? 'electronic' : 'paper',
          status: this.getStatusClass(item.status),
          statusText: this.getStatusText(item.status),
          createTime: item.createTime,
          title: item.invoiceTitle,
          content: '出租车服务费',
          code: item.taxNumber || '-',
          amount: item.amount.toFixed(2),
          fileUrl: item.fileUrl,
          email: item.contactEmail || '-'
        }));

        if (this.pageNum === 1) {
          this.invoiceList = list;
        } else {
          this.invoiceList = [...this.invoiceList, ...list];
        }

        this.hasMore = list.length === this.pageSize;
      } catch (error) {
        console.error('获取开票记录失败', error);
      } finally {
        this.loading = false;
      }
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '处理中',
        2: '已完成',
        3: '已取消'
      };
      return statusMap[status] || '待处理';
    },
    // 获取状态样式
    getStatusClass(status) {
      const statusClassMap = {
        0: 'processing',
        1: 'processing',
        2: 'success',
        3: 'failed'
      };
      return statusClassMap[status] || 'processing';
    },
  },
};
</script>

<style lang="scss" scoped>
.invoice-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;

  .header-bg {
    background: linear-gradient(180deg, #3175ff 0%, #3175ff 100%);
    padding-bottom: 40rpx;
    border-radius: 0 0 40rpx 40rpx;

    .nav-bar {
      display: flex;
      align-items: center;
      padding: 88rpx 30rpx 20rpx;

      .back {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .iconfont {
          color: #fff;
          font-size: 40rpx;
        }
      }

      .title {
        flex: 1;
        text-align: center;
        color: #fff;
        font-size: 36rpx;
        font-weight: 500;
        margin-right: 60rpx;
      }
    }

    .header-content {
      padding: 30rpx;

      .total-info {
        display: flex;
        flex-direction: column;
        align-items: center;

        .label {
          color: rgba(255, 255, 255, 0.8);
          font-size: 28rpx;
          margin-bottom: 20rpx;
        }

        .amount {
          color: #fff;
          font-size: 60rpx;
          font-weight: bold;
        }
      }

      .stat-row {
        display: flex;
        justify-content: space-around;
        margin-top: 40rpx;

        .stat-item {
          display: flex;
          flex-direction: column;
          align-items: center;

          .num {
            color: #fff;
            font-size: 40rpx;
            font-weight: bold;
            margin-bottom: 10rpx;
          }

          .label {
            color: rgba(255, 255, 255, 0.8);
            font-size: 26rpx;
          }
        }
      }
    }
  }

  .new-invoice-btn {
    margin: 30rpx;
    height: 100rpx;
    background: #fff;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

    .icon {
      width: 48rpx;
      height: 48rpx;
      margin-right: 20rpx;
    }

    text {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }
  }

  .invoice-list {
    padding: 0 30rpx;

    .list-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .title {
        font-size: 34rpx;
        font-weight: bold;
        color: #333;
      }

      .subtitle {
        font-size: 26rpx;
        color: #999;
        margin-left: 20rpx;
      }
    }

    .invoice-item {
      background: #fff;
      border-radius: 20rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;

      .invoice-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;

        .left {
          display: flex;
          align-items: center;

          .type {
            font-size: 30rpx;
            font-weight: 500;
            color: #333;
          }

          .status {
            margin-left: 20rpx;
            font-size: 24rpx;
            padding: 4rpx 16rpx;
            border-radius: 20rpx;

            &.success {
              color: #52c41a;
              background: rgba(82, 196, 26, 0.1);
            }

            &.processing {
              color: #3175ff;
              background: rgba(49, 117, 255, 0.1);
            }

            &.failed {
              color: #ff4d4f;
              background: rgba(255, 77, 79, 0.1);
            }
          }
        }

        .time {
          font-size: 26rpx;
          color: #999;
        }
      }

      .invoice-content {
        .info-row {
          display: flex;
          margin-bottom: 16rpx;

          .label {
            color: #666;
            font-size: 28rpx;
            width: 180rpx;
          }

          .value {
            flex: 1;
            color: #333;
            font-size: 28rpx;
          }
        }
      }

      .invoice-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20rpx;
        padding-top: 20rpx;
        border-top: 2rpx solid #f5f5f5;

        .amount {
          font-size: 36rpx;
          font-weight: bold;
          color: #ff6b00;
        }

        .action-btns {
          display: flex;
          align-items: center;
          flex-shrink: 0;
          margin-left: 20rpx;

          .btn {
            padding: 8rpx 20rpx;
            border-radius: 30rpx;
            font-size: 24rpx;
            margin-left: 16rpx;
            white-space: nowrap;

            &.preview {
              color: #52c41a;
              background: rgba(82, 196, 26, 0.1);
              margin-right: 16rpx;
            }

            &.download {
              color: #3175ff;
              background: rgba(49, 117, 255, 0.1);
            }
          }
        }
      }
    }
  }

  .bottom-tips {
    text-align: center;
    color: #999;
    font-size: 26rpx;
    padding: 30rpx 0;
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 200rpx;

    .empty-img {
      width: 300rpx;
      height: 300rpx;
      margin-bottom: 30rpx;
    }

    .empty-text {
      color: #999;
      font-size: 28rpx;
    }
  }
}
</style>
